﻿using Mapster;
using System.Linq.Expressions;

namespace YiShop.Framework
{
    public abstract class BaseService<TEntity, TDto> : ITransient
        where TEntity : BaseEntity, new()
        where TDto : BaseDto, new()
    {
        public virtual required BaseRepository<TEntity, TDto> BaseRepo { get; set; }

        /// <summary>
        /// 查询
        /// </summary>
        public virtual async Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await BaseRepo.FirstOrDefaultAsync(predicate);
        }

        //分页
        public async Task<SqlSugarPagedList<TDto>> GetDtoPagedListAsync(TDto dto)
        {
            return await BaseRepo.GetDtoPagedListAsync(dto);
        }
        //分页
        public virtual async Task<SqlSugarPagedList<TEntity>> GetPagedListAsync(TDto dto)
        {
            return await BaseRepo.GetPagedListAsync(dto);
        }

        /// <summary>
        /// 查询 List 
        /// </summary>
        public virtual async Task<List<TEntity>> GetListAsync(TDto dto)
        {
            return await BaseRepo.GetListAsync(dto);
        }

        /// <summary>
        /// 查询 Dto List 
        /// </summary>
        public virtual async Task<List<TDto>> GetDtoListAsync(TDto dto)
        {
            return await BaseRepo.GetDtoListAsync(dto);
        }


        #region 增删改
        /// <summary>
        /// 新增
        /// </summary>
        public virtual async Task<bool> InsertAsync(TEntity entity)
        {
            return await BaseRepo.InsertAsync(entity);
        }

        public async Task<bool> InsertAsync(TDto dto)
        {
            var entity = dto.Adapt<TEntity>();
            return await InsertAsync(entity);
        }

        /// <summary>
        /// 更新
        /// </summary>
        public virtual async Task<int> UpdateAsync(TEntity entity)
        {
            return await BaseRepo.UpdateAsync(entity);
        }

        /// <summary>
        /// 更新: 按 dto
        /// </summary>
        public virtual async Task<int> UpdateAsync(TDto dto)
        {
            var entity = dto.Adapt<TEntity>();
            return await UpdateAsync(entity);
        }

        /// <summary>
        /// 按 key 删除
        /// </summary>
        public virtual async Task<int> DeleteAsync(long key)
        {
            return await BaseRepo.DeleteAsync(key);
        }

        /// <summary>
        /// 按 key 删除
        /// </summary>
        public virtual async Task<int> DeleteAsync(long[] keys)
        {
            return await BaseRepo.DeleteAsync(keys);
        }
        #endregion
    }
}
